package cmd_handler

import (
	"google.golang.org/protobuf/reflect/protoreflect"
	"google.golang.org/protobuf/types/dynamicpb"
	"xgame.go_server/comm/lazy_save"
	"xgame.go_server/lso"
	"xgame.go_server/model"
	"xgame.go_server/msg"
)

// 初始化
func init() {
	handleFuncMap[int32(msg.E_MsgCode_Game_USER_ATTK_CMD.Number())] = handleUserAttkCmd
}

// 处理攻击指令
func handleUserAttkCmd(ctx MyCmdCtx, pbMsgObj *dynamicpb.Message) {
	if nil == ctx ||
		nil == pbMsgObj {
		return
	}

	userAttkCmd := &msg.UserAttkCmd{}

	pbMsgObj.Range(func(f protoreflect.FieldDescriptor, v protoreflect.Value) bool {
		userAttkCmd.ProtoReflect().Set(f, v)
		return true
	})

	userAttkResult := &msg.UserAttkResult{
		AttkUserId:   uint32(ctx.GetUserId()),
		TargetUserId: userAttkCmd.TargetUserId,
	}

	getBroadcaster().broadcast(userAttkResult)

	// 获取用户数据
	user := model.GetUserGroup().GetByUserId(int64(userAttkCmd.GetTargetUserId()))

	if nil == user {
		// 如果攻击目标为空,
		// 就直接退出
		return
	}

	var subtractHp int32 = 10
	user.CurrHp -= subtractHp // XXX 注意: 要给 user.go 增加 CurrHp 字段

	userSubtractHpResult := &msg.UserSubtractHpResult{
		SubtractHp:   uint32(subtractHp),
		TargetUserId: userAttkCmd.TargetUserId,
	}

	getBroadcaster().broadcast(userSubtractHpResult)

	if user.CurrHp <= 0 {
		getBroadcaster().broadcast(
			&msg.UserDieResult{
				TargetUserId: userAttkCmd.TargetUserId,
			},
		)
	}

	// 延迟保存用户数据
	userLso := lso.GetUserLso(user)

	lazy_save.SaveOrUpdate(userLso)
}
